package com.erp.app.common.VUtil.io;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.Reader;

public class UnicodeReader extends Reader {

    public String DEFAULT_ENCODING = "default";
    InputStreamReader isr;
    String encoding = DEFAULT_ENCODING;

    public UnicodeReader(byte b[]) throws IOException {
        this(new ByteArrayInputStream(b));
    }

    public UnicodeReader(File f) throws FileNotFoundException, IOException {
        this(new FileInputStream(f));
    }

    public UnicodeReader(InputStream in) throws IOException {
        PushbackInputStream pbis = new PushbackInputStream(in, 3);
        try {
            int x, y, z;

            x = pbis.read();
            y = pbis.read();
            z = pbis.read();
            pbis.unread(z);
            pbis.unread(y);
            pbis.unread(x);

            if (0xff == x && 0xfe == y) {
                pbis.skip(2);
                encoding = "UTF-16LE";
            } else if (0xfe == x && 0xff == y) {
                pbis.skip(2);
                encoding = "UTF-16BE";
            } else if (0xef == x && 0xbb == y && 0xbf == z) {
                pbis.skip(3);
                encoding = "UTF-8";
            }
            isr = new InputStreamReader(pbis, encoding);
        } catch (Exception e) {
            if (null != pbis)
                pbis.close();
            e.printStackTrace();
        } finally {
            if (null == isr) {
                isr = new InputStreamReader(in);
            }
        }
    }

    public String getEncoding() {
        return encoding;
    }

    public boolean isDefaultEncoding() {
        return DEFAULT_ENCODING.equals(encoding);
    }

    public void close() throws IOException {
        isr.close();
    }

    public void mark(int readAheadLimit) throws IOException {
        isr.mark(readAheadLimit);
    }

    public int read(char[] cbuf, int off, int len) throws IOException {
        return isr.read(cbuf, off, len);
    }

    public boolean ready() throws IOException {
        return isr.ready();
    }

    public void reset() throws IOException {
        isr.reset();
    }

    public long skip(long n) throws IOException {
        return isr.skip(n);
    }

    public static void main(String args[]) throws Exception {
        BufferedReader in = new BufferedReader(new UnicodeReader(new File(args[0])));
        while (in.ready())
            System.out.println(in.readLine());
    }
}
